package com.standard.logcat.exceptionHandler

import com.standard.logcat.sp.ExceptionLogValue
import java.text.SimpleDateFormat
import java.util.*

object UncaughtExceptionHandler : Thread.UncaughtExceptionHandler {

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA)

    //系统的默认异常处理类
    private var defaultExceptionHandler: Thread.UncaughtExceptionHandler? = null

    fun init() {
        defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(this)
    }

    override fun uncaughtException(t: Thread, e: Throwable) {

        val buffer = StringBuffer()
        buffer.apply {
            append(dateFormat.format(Date()))
            append("\n")
            append("\n")
            append("异常描述:")
            append("\n")
            append(e.toString())
            append("\n")
            append("\n")
            append("异常发生在:")
            append("\n")
            for (element in e.stackTrace) {
                //过滤掉包名以android、kotlin、java开头的类
                if (element.className.startsWith("android") ||
                    element.className.startsWith("kotlin") ||
                    element.className.startsWith("java")
                ) {
                    continue
                }
                append(element.fileName)
                append("\n")
                append(element.className)
                append("\n")
                append("行号:")
                append(element.lineNumber)
                append("\n")
                append("\n")
            }
        }
        ExceptionLogValue.exception = buffer.toString()

        //如果系统提供了异常处理类，则交给系统去处理
        if (defaultExceptionHandler != null) {
            defaultExceptionHandler?.uncaughtException(t, e)
        }
    }
}